import { useState, useCallback, useMemo } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import type { TablePagination, TableSearchField } from './types';

interface UseTableOptions<T = any> {
  queryKey: string;
  fetchData: (params: TableFetchParams) => Promise<TableFetchResponse<T>>;
  defaultPageSize?: number;
  searchFields?: TableSearchField[];
  defaultSort?: {
    field: string;
    order: 'ascend' | 'descend';
  };
  onSuccess?: (data: TableFetchResponse<T>) => void;
  onError?: (error: any) => void;
}

interface TableFetchParams {
  page: number;
  pageSize: number;
  search?: Record<string, any>;
  sort?: {
    field: string;
    order: 'ascend' | 'descend';
  };
}

interface TableFetchResponse<T> {
  data: T[];
  total: number;
  page: number;
  pageSize: number;
}

export const useTable = <T extends Record<string, any>>(options: UseTableOptions<T>) => {
  const {
    queryKey,
    fetchData,
    defaultPageSize = 10,
    searchFields = [],
    defaultSort,
    onSuccess,
    onError,
  } = options;

  
  // 状态管理
  const [paginationState, setPaginationState] = useState({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  });

  // 处理分页变化
  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setPaginationState(prev => ({
      ...prev,
      current: page,
      pageSize,
    }));
  }, []);

  const pagination: TablePagination = {
    current: paginationState.current,
    pageSize: paginationState.pageSize,
    total: paginationState.total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
  };

  const [searchParams, setSearchParams] = useState<Record<string, any>>({});
  const [sortParams, setSortParams] = useState<{
    field: string;
    order: 'ascend' | 'descend';
  } | undefined>(defaultSort);

  // 使用 useMemo 来创建 queryKey，确保依赖变化时重新计算
  const currentQueryKey = useMemo(() => {
    const key = [
      queryKey,
      paginationState.current,
      paginationState.pageSize,
      JSON.stringify(searchParams),
      sortParams ? JSON.stringify(sortParams) : undefined
    ];
    return key;
  }, [queryKey, paginationState.current, paginationState.pageSize, searchParams, sortParams]);

  // 获取数据
  const {
    data: tableData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: currentQueryKey,
    queryFn: async () => {
      const actualPage = currentQueryKey[1];
      const actualPageSize = currentQueryKey[2];

      const params: TableFetchParams = {
        page: actualPage,
        pageSize: actualPageSize,
        search: Object.keys(searchParams).length > 0 ? searchParams : undefined,
        sort: sortParams,
      };

      try {
        const response = await fetchData(params);
        // 更新分页信息
        setPaginationState(prev => ({
          ...prev,
          total: response.total,
        }));

        onSuccess?.(response);
        return response;
      } catch (error) {
        onError?.(error);
        throw error;
      }
    },
    enabled: true,
    placeholderData: (previousData) => previousData,
  });

  

  // 处理搜索
  const handleSearch = useCallback((params: Record<string, any>) => {
    setSearchParams(params);
    setPaginationState(prev => ({
      ...prev,
      current: 1,
    }));
  }, []);

  // 重置搜索
  const handleResetSearch = useCallback(() => {
    setSearchParams({});
    setPaginationState(prev => ({
      ...prev,
      current: 1,
    }));
  }, []);

  // 处理排序
  const handleSort = useCallback((sorter: any) => {
    if (sorter.field && sorter.order) {
      setSortParams({
        field: sorter.field,
        order: sorter.order,
      });
    } else {
      setSortParams(undefined);
    }
  }, []);

  const handleFilter = useCallback((filters: Record<string, any>) => {
    const filterParams: Record<string, any> = {};
    Object.keys(filters).forEach(key => {
      if (filters[key] && filters[key].length > 0) {
        filterParams[key] = filters[key];
      }
    });
    setSearchParams(prev => ({
      ...prev,
      ...filterParams,
    }));
    setPaginationState(prev => ({
      ...prev,
      current: 1,
    }));
  }, []);

  const handleTableChange = useCallback((newPagination: TablePagination, filters: Record<string, any>, sorter: any) => {
    handlePaginationChange(newPagination.current, newPagination.pageSize);
    handleFilter(filters);
    handleSort(sorter);
  }, [handlePaginationChange, handleFilter, handleSort]);

  const refresh = useCallback(() => {
    refetch();
  }, [refetch]);

  const getData = useCallback(() => {
    return tableData?.data || [];
  }, [tableData]);

  const getTotal = useCallback(() => {
    return tableData?.total || 0;
  }, [tableData]);

  const exportData = useCallback(async (format: 'csv' | 'excel' | 'pdf') => {
    try {
      // 导出功能待实现
    } catch (error) {
      // 导出错误处理
    }
  }, [getData, searchParams, sortParams]);

  const deleteMutation = useMutation({
    mutationFn: async (ids: (string | number)[]) => {
      // 这里应该调用实际的删除 API
      return Promise.resolve();
    },
    onSuccess: () => {
      refetch();
    },
  });

  const handleDelete = useCallback((ids: (string | number)[]) => {
    deleteMutation.mutate(ids);
  }, [deleteMutation]);

  return {
    data: getData(),
    total: getTotal(),
    loading: isLoading,
    error,
    pagination,
    searchParams,
    searchFields,
    handleSearch,
    handleResetSearch,
    handleTableChange,
    refresh,
    exportData,
    handleDelete,
    deleteLoading: deleteMutation.isLoading,
  };
};